//
//  CollectionVideoViewController.m
//  miaopai
//
//  Created by duyifang on 15/11/14.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "CollectionVideoViewController.h"
#import "CustomerNetworking.h"
#import "Channel.h"
#import "CollectionVideoTableViewCell.h"
#import "AutoadaptationFrame.h"
#import "Ext.h"
#import "MyselfAVPlayer.h"
#import "CustomerAVPlayer.h"
#import "SCCatWaitingHUD.h"

#import "TopicDetailViewController.h"

#import "VideoDetailViewController.h"

@interface CollectionVideoViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, CollectionVideoTableViewCellDelegate>

@property(nonatomic, retain) UITableView *tableView;

@property(nonatomic, retain) NSMutableArray *modelArray;

@property(nonatomic, assign) CGFloat lastContentOffsetY;

@property(nonatomic, retain)NSIndexPath *lastIndexPath;

@end

@implementation CollectionVideoViewController

- (void)dealloc
{
    [_tableView release];
    [_modelArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.modelArray = [NSMutableArray array];
    self.title = @"合辑";
    [[SCCatWaitingHUD sharedInstance] animateWithInteractionEnabled:YES];
    [self downloadData];
    [self creatSubView];
}

- (void)downloadData
{
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://api.miaopai.com/m/v2_topic.json?os=ios&page=1&per=20&stpid=%@&type=0&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1", self.stpid] andparameters:nil andBlock:^(id response) {
        [[SCCatWaitingHUD sharedInstance] stop];
        NSDictionary *bigDic = response;
        NSArray *topicArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in topicArray) {
            Channel *channel = [Channel channelWithDic:[dic objectForKey:@"channel"]];
            if ([[[dic objectForKey:@"channel"] objectForKey:@"topicinfo"] isKindOfClass:[NSDictionary class]]){
                channel.topics = [[[dic objectForKey:@"channel"] objectForKey:@"topicinfo"] allValues];
            }else
            {
                channel.topics = [[dic objectForKey:@"channel"] objectForKey:@"topicinfo"];
            }
            [_modelArray addObject:channel];
        }
        [_tableView reloadData];
    }];
}

- (void)creatSubView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.backgroundColor = [UIColor colorWithRed:0.9063 green:0.9063 blue:0.9063 alpha:1.0];
    [_tableView setContentInset:UIEdgeInsetsMake(0, 0, -48, 0)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[CollectionVideoTableViewCell class] forCellReuseIdentifier:@"CollectionVideoTableViewCell"];
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView.tableFooterView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectionVideoTableViewCell" forIndexPath:indexPath];
    Channel *channel = [_modelArray objectAtIndex:indexPath.row];
    cell.channel = channel;
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.row == 0) {
        cell.stream = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
    }
    cell.delegate = self;
    return cell;
}

- (void)toTopicView:(NSString *)topicName
{
    TopicDetailViewController *topicView = [[TopicDetailViewController alloc] init];
    topicView.topicName = topicName;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
    [self.navigationController pushViewController:topicView animated:YES];
    [topicView release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Channel *channel = (Channel *)[_modelArray objectAtIndex:indexPath.row];
    CGFloat topHeight = 50.5;
    CGFloat avplayerHeight = self.view.frame.size.width * 3 / 4;
    CGFloat introduceLabelHeight = [AutoadaptationFrame heightOfLabel:channel.ext.t andTextFont:[UIFont systemFontOfSize:15] andLabelWidth:self.view.frame.size.width - 20];
    CGFloat buttonHeight = 50;
    return topHeight + avplayerHeight + introduceLabelHeight + buttonHeight + 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    VideoDetailViewController *videoDetailViewController = [[VideoDetailViewController alloc] init];
    Channel *channel = [_modelArray objectAtIndex:indexPath.row];
    videoDetailViewController.scid = channel.scid;
    [self.navigationController pushViewController:videoDetailViewController animated:YES];
    [videoDetailViewController release];

//    Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
//    VideoDetailViewController *videoView = [[VideoDetailViewController alloc] init];
//    videoView.scid = channel.scid;
//    [self.navigationController pushViewController:videoView animated:YES];
//    [videoView release];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //NSLog(@"苹果%lf",self.tableView.contentOffset.y);
    if (self.tableView.contentOffset.y < 0) {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
            CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
            cell.stream = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
            self.lastIndexPath = indexPath;
        }
    }else
    {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSArray *array = [self.tableView indexPathsForVisibleRows];
            if (![array containsObject:self.lastIndexPath]) {
                CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:self.lastIndexPath];
                cell.removeVideo = @"a";
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"======%lf",self.tableView.contentOffset.y);
    if (self.tableView.contentOffset.y < 0) {
        
    }else
    {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:1];
            self.lastIndexPath = indexPath;
            CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
            cell.stream = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.tableView.contentOffset.y < 0) {
        
    }else
    {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:1];
            self.lastIndexPath = indexPath;
            CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
            cell.stream = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
        }
    }

}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    NSLog(@"411111");
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"%lf", self.tableView.contentOffset.y);
    //[self scrollViewDidEndScrollingAnimation:self.tableView];
    if (self.tableView.contentOffset.y < 30) {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
            CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
            cell.playURL = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
            self.lastIndexPath = indexPath;
        }
    }else
    {
        if ([self.tableView indexPathsForVisibleRows].count > 0) {
            NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:1];
            self.lastIndexPath = indexPath;
            CollectionVideoTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
            Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
            cell.playURL = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[CustomerAVPlayer shareCustomerAVPlayer] stop];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
